package moonhy.c2dm_client;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;

public class TabHostActivity extends TabActivity{
	private SharedPreferences prefs;
	private OnSharedPreferenceChangeListener listener;
	
	private View createTabView(Context context, String text, int idx) {
		View view = LayoutInflater.from(context).inflate(R.layout.main_tab_layout, null);
		TextView tv = (TextView) view.findViewById(R.id.tabsText);
		ImageView iv = (ImageView) view.findViewById(R.id.tabIcon);
		
		tv.setText(text);
		
		Drawable dw;
		switch(idx){
			case 0:
				dw = getResources().getDrawable(R.drawable.tab_home);
				iv.setImageDrawable(dw);
				break;
			case 1:
				dw = getResources().getDrawable(R.drawable.tab_chat);
				iv.setImageDrawable(dw);
				break;
			case 2:
				dw = getResources().getDrawable(R.drawable.tab_account);
				iv.setImageDrawable(dw);
				break;
			case 3:
				dw = getResources().getDrawable(R.drawable.tab_settings);
				iv.setImageDrawable(dw);
				break;
		}
		
		
		if(idx == 1){
			TextView MsgCount = (TextView) view.findViewById(R.id.MsgCount);
			int totCount = prefs.getInt("UnreadCntTotal", 0);
			
			if(totCount > 0){
				MsgCount.setVisibility(View.VISIBLE);
				MsgCount.setText("" + totCount);
			}else{
				MsgCount.setVisibility(View.INVISIBLE);
			}
		}
		
		return view;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setContentView(R.layout.main);
		Resources res = getResources();
		
		int open_room = -1;
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			open_room = extras.getInt("frm_room_no", -1);
		}
		
		prefs = PreferenceManager.getDefaultSharedPreferences(TabHostActivity.this);
		int openedTab = prefs.getInt("currentTab", 0);
		
		final TabHost tabHost = getTabHost();
		//tabHost.getTabWidget().setDividerDrawable(R.drawable.tab_divider);
		
		
		NotificationManager notice = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
		notice.cancelAll();
		
		//tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("Main", res.getDrawable(android.R.drawable.star_big_on))
				//.setContent(new Intent(this, MainActivity.class)));
		final View tab1 = createTabView(tabHost.getContext(), "규라인", 0);
		tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator(tab1)
				.setContent(new Intent(this, MainViewFlowActivity.class)));
		final View tab2 = createTabView(tabHost.getContext(), "메시지", 1);
		tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator(tab2)
				.setContent(new Intent(this, ChatListActivity.class).putExtra("frm_room_no", open_room)));
		final View tab3 = createTabView(tabHost.getContext(), "회계", 2);
		tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator(tab3)
				.setContent(new Intent(this, AccountActivity.class)));
//		tabHost.addTab(tabHost.newTabSpec("tab4").setIndicator("Notices")
//				.setContent(new Intent(this, MessageReceivedActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)));
		final View tab4 = createTabView(tabHost.getContext(), "More", 3);
		tabHost.addTab(tabHost.newTabSpec("tab4").setIndicator(tab4)
				.setContent(new Intent(this, MoreActivity.class)));
		
		// 처음 등록된 Tab을 보여줌.
		tabHost.setCurrentTab(openedTab);
		
		tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
			@Override
			public void onTabChanged(String tabId) {
				if(tabId.equals("tab1")){
					Editor edit = prefs.edit();
					edit.putInt("currentTab",0).commit();
				}
			}
		});
		
		
		// Shared Preference 변경 이벤트
		
		listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
			@Override
			public void onSharedPreferenceChanged(SharedPreferences arg0, String key) {
				
				Log.i("C2DM", "[TabHost Event Fired] onSharedPreferenceChanged key: " + key);

				if (key.equalsIgnoreCase("UnreadCntTotal")) {
					TextView tv = (TextView) tabHost.getTabWidget().getChildAt(1).findViewById(R.id.MsgCount);
					int totCount = prefs.getInt("UnreadCntTotal", 0);
					
					if(totCount > 0){
						tv.setVisibility(View.VISIBLE);
						tv.setText("" + totCount);
					}else{
						tv.setVisibility(View.INVISIBLE);
					}
				}
			}
		};
		prefs.registerOnSharedPreferenceChangeListener(listener);
		
		
        
        /*
        tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
			@Override
			public void onTabChanged(String tabId) {
				startActivity(i3);
				
				// TODO Auto-generated method stub
				for(int i = 0; i < tabHost.getTabWidget().getChildCount(); i++){
					if(i == tabHost.getCurrentTab()){
						tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#0B3747"));
					}else{
						tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#000000"));
					}
				}
				
				if(tmp_nd.getContent() == null){
					new initPage(tabHost.getTabWidget().getChildAt(0).getContext()).execute();
				}
				if(nd_array.getContent() == null){
					new initPage(tabHost.getTabWidget().getChildAt(0).getContext()).execute();
				}
				new initPage(tabHost.getTabWidget().getChildAt(3).getContext()).execute();
				 
			}
		});
         */
        
        
        /*
        tabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#0B3747"));
        tabHost.getTabWidget().getChildAt(1).setBackgroundColor(Color.parseColor("#05171F"));
        tabHost.getTabWidget().getChildAt(2).setBackgroundColor(Color.parseColor("#05171F"));
        tabHost.getTabWidget().getChildAt(3).setBackgroundColor(Color.parseColor("#05171F"));
        */
		
		/*
		TabHost tabHost = (TabHost)findViewById(R.id.tabHost);
        
        // findViewById를 이용해 TabHost인스턴스를 얻은경우 꼭 호출 필요
        tabHost.setup();
        
        // Tab builder 객체 
        TabHost.TabSpec spec;
          
        // Tab 01 세팅 & 등록 
        spec = tabHost.newTabSpec("Tab 00"); // Tab Builder 객체 생성
        spec.setIndicator("Main");			// Tab 제목
        spec.setContent(R.id.layout);		// Tab 내용
        tabHost.addTab(spec);				// Tab 등록
        
        // Tab 02 세팅 & 등록
        spec = tabHost.newTabSpec("Tab 01"); // Tab Builder 객체 생성
        spec.setIndicator("Members");		// Tab 제목
        spec.setContent(R.id.layout2);	// Tab 내용
        tabHost.addTab(spec);				// Tab 등록
        
        // Tab 03 세팅 & 등록
        spec = tabHost.newTabSpec("Tab 02"); // Tab Builder 객체 생성
        spec.setIndicator("회비사용내역");		// Tab 제목
        spec.setContent(R.id.layout2);	// Tab 내용
        tabHost.addTab(spec);				// Tab 등록
        
        // Tab 04 세팅 & 등록
        spec = tabHost.newTabSpec("Tab 03"); // Tab Builder 객체 생성
        spec.setIndicator("공지사항");		// Tab 제목
        spec.setContent(new Intent(this, MessageReceivedActivity.class));		// Tab 내용
        tabHost.addTab(spec);				// Tab 등록
        
        //tabHost.getTabWidget().getChildAt(0).getLayoutParams().height = 80; 
        //tabHost.getTabWidget().getChildAt(1).getLayoutParams().height = 80;
        //tabHost.getTabWidget().getChildAt(2).getLayoutParams().height = 80;
        //tabHost.getTabWidget().getChildAt(3).getLayoutParams().height = 80;
        
        //tabHost.getTabWidget().getChildAt(0).setBackgroundColor(0xFF5071CB);
        //tabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#4E4E9C"));
        
        
        // 처음 등록된 Tab을 보여줌.
        tabHost.setCurrentTab(0);
        
		//search 버튼 이벤트 리스너
		Button viewNotice = (Button)findViewById(R.id.viewNotice);
		viewNotice.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});
		
		
		Button viewRegistrationID = (Button)findViewById(R.id.viewRegistrationID);
		viewRegistrationID.setOnClickListener(viewRegistrationID_listener);
		*/
        /*
		final String googleAccount = getUsername();
		if( googleAccount == null){
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Google의 계정을 먼저 생성 하신 후 사용하시기 바랍니다.")
			       .setCancelable(false)
			       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	   C2DM_ClientActivity.this.finish();
			           }
			       });
			AlertDialog alert = builder.create();
			alert.show();
		}else{
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
			String authString = prefs.getString(AUTH, "n/a");
			
			if(authString.equals("n/a")){ 
				
				Log.d("C2DM", "phone #: " + getMyPhoneNumber() + "email: " + googleAccount);
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setMessage("사용자 인증을 아직 받지 않았습니다. 지금 인증하시겠습니까?")
				       .setCancelable(false)
				       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				        	   //C2DM_ClientActivity.this.finish();
				        	   register(googleAccount);
				           }
				       })
				       .setNegativeButton("No", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				        	   C2DM_ClientActivity.this.finish();
				           }
				       });
				       
				AlertDialog alert = builder.create();
				alert.show();
			}else{
				new initPage().execute();
			}
		}
         */
        
	}
	
	@Override
	public void onResume(){
		super.onResume();
		prefs.registerOnSharedPreferenceChangeListener(listener);
		
		NotificationManager notice = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
		notice.cancelAll();
	}
	
}